<template>
  <div v-if="tabList && tabList.length > 0">
    <scroll-view
      scroll-x
      :show-scrollbar="false"
      :scroll-left="scrollLeft"
      scroll-with-animation
    >
      <div class="tab-list" :style="boxStyle">
        <div class="tab-item" v-if="config.defaultFlag == '1'">
          {{ config.defaultTitle || "首页" }}
          <span :style="'background:' + config.fontColor" class="tab-item-border"></span>
        </div>
        <div
          :style="boxStyle"
          class="tab-item"
          @click="toDetail(item.href, index)"
          v-for="(item, index) in tabList"
          :key="index"
        >
          {{ item.title }}
        </div>
      </div>
    </scroll-view>
  </div>
</template>
<script>
import { getPageGroupList } from "@/api/public";
export default {
  name: "tab-list",
  props: {
    config: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      tabList: [],
      scrollLeft: 0,
    };
  },
  watch: {
    "config.customFlag"() {
      this.getData();
    },
  },
  mounted() {
    this.getData();
  },
  computed: {
    boxStyle() {
      let background = this.config.backgroundColor || "#FF7300";
      let color = this.config.fontColor || "#ffffff";
      return `background: ${background};color:${color};`;
    },
  },
  methods: {
    getData() {
      if (this.config.customFlag == "1") {
        this.tabList = this.config.tabList;
      } else {
        this.getPageGroupList();
      }
    },
    //获取分组列表
    getPageGroupList() {
      let param = {
        page: 1, //页码
        limit: 20, //页大小
      };
      getPageGroupList(param)
        .then((res) => {
          console.log("获取分组列表----------------------", res.data);
          res.data.forEach((item) => {
            item.title = item.cateName;
            item.href = `/pages/shop/ClasssList/main?id=${item.id}&title=${item.cateName}`;
          });
          this.tabList = res.data;
        })
        .catch((err) => {
          console.log("获取分组列表失败----------------------", err);
        });
    },
    toDetail(url, index) {
      this.scrollLeft = (index - 1) * 80;
      wx.navigateTo({
        url: url,
      });
    },
  },
};
</script>
<style scoped>
.tab-list {
  text-align: center;
  white-space: nowrap;
}
.tab-item {
  position: relative;
  display: inline-block;
  vertical-align: middle;
  height: 90rpx;
  line-height: 90rpx;
  /* min-width: 200rpx; */
  padding: 0 20px;
  max-width: 240rpx;
  overflow: hidden;
  text-overflow: ellipsis;
}
.tab-item-border {
  position: absolute;
  width: 80rpx;
  height: 6rpx;
  background: #fff;
  left: calc((100% - 80rpx) / 2);
  bottom: 0;
}
</style>
